from typing import Literal

from langchain_core.messages import SystemMessage, HumanMessage
from langchain_openai import ChatOpenAI
from langchain_core.tools import tool
from langgraph.graph import END,START,StateGraph,MessagesState  #核心组件End，start，stategraph，messagestate
from langgraph.prebuilt import ToolNode

import common.openai_ali


@tool
def search(query:str):
    """设计网页搜索工具"""
    return "It's 32 degress and sunny"

tools = [search]  #将工具放入工具列表
tool_node = ToolNode(tools) #创建toolnode，工具列表封装成langgraph节点
model = ChatOpenAI(
        model="qwen-plus",  # 阿里云千问-plus模型
        openai_api_key='sk-965dc39b016c49ecbe29de180f4db2b6',
        openai_api_base='https://dashscope.aliyuncs.com/compatible-mode/v1',
        temperature=0.7,  # 控制生成文本的随机性
        max_tokens=2048,  # 最大生成长度
    )

model.bind_tools(tools)
workflow = StateGraph(MessagesState)


def call_model(state):
    messages = state['messages']
    resonse = model.invoke(messages)
    return {"messages":[resonse]}

workflow.add_node("agent",call_model)
# https://goen.win/auto/jackzhou/dff41dda
workflow.add_node("tools",tool_node)

workflow.set_entry_point("agent")
#定义条件函数
def should_continue(state):
    messages  = state['messages']
    last_message = messages[-1]
    if last_message.tool_calls :
        return "tools"
    return END

#添加边
# 添加条件边：从 "agent" 节点出发，根据 should_continue 函数的返回值，决定流向 "tools" 节点或 END
workflow.add_conditional_edges(
    "agent", # 起始节点为 "agent" 节点
    should_continue # 条件判断函数为 should_continue
)
# 添加普通边：从 "tools" 节点到 "agent" 节点，表示工具调用完成后，总是返回 agent 节点继续推理
workflow.add_edge("tools", 'agent')
# 编译 LangGraph 图，得到可执行的 app 对象
app = workflow.compile()
# 运行智能体应用 app，处理用户查询 "What is the weather in sf" (旧金山天气)
final_state = app.invoke({"messages": [{"role": "user", "content": "what is the weather in sf"}]})
# 打印智能体的最后一条回复消息的内容
print(final_state["messages"][-1].content)
